package com.king.zkrpc.common.server;

import org.apache.zookeeper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.king.zkrpc.common.protocol.Constant;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 连接ZK注册中心，创建服务注册目录
 */
public class ServiceRegistry {

    private static final Logger LOGGER = LoggerFactory.getLogger(ServiceRegistry.class);

    private CountDownLatch latch = new CountDownLatch(1);

    private String registryAddress;

    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    public void register(String serverAddress,List<String> interfaceList) {
        if (interfaceList != null && serverAddress != null) {
            ZooKeeper zk = connectServer();
            if (zk != null) {
                createNode(zk, serverAddress,interfaceList);
            }
        }
    }

    private ZooKeeper connectServer() {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(registryAddress, Constant.ZK_SESSION_TIMEOUT, new Watcher() {
                public void process(WatchedEvent event) {
                    // 判断是否已连接ZK,连接后计数器递减.
                    if (event.getState() == Event.KeeperState.SyncConnected) {
                        latch.countDown();
                    }
                }
            });

            // 若计数器不为0,则等待.
            latch.await();
        } catch (InterruptedException e) {
            LOGGER.error("", e);
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return zk;
    }

    private void createNode(ZooKeeper zk, String serverAddress,List<String> interfaceList ) {
        try {
            LOGGER.debug(" the interfaceList's size is " + interfaceList.size());

            String path = null;
            for (String inf :interfaceList) {

                if (zk.exists("/" + inf, false) == null){

                    zk.create("/" + inf, "".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                }

                path = "/" + inf + "/" + serverAddress;
                if(zk.exists(path, false) != null){// 当前节点存在，就删除。
                    LOGGER.debug(" the node is exists, delete it!!!!!!!!!!!!!!!!!!!!!!!!!!!! ");
                    zk.delete(path,-1);
                }

                byte[] bytes = serverAddress.getBytes();
                zk.create(path, bytes, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                LOGGER.debug("create zookeeper node ({} => {})", path, serverAddress);

            }


        } catch (KeeperException e) {
            LOGGER.error("", e);
        } catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}